/*
  This file is a part of hashutils package.
  (c) 2004 Zeljko Vrba <zvrba@globalnet.hr>

  Permission is hereby granted, free of charge, to any person obtaining
  a copy of this software and associated documentation files (the
  "Software"), to deal in the Software without restriction, including
  without limitation the rights to use, copy, modify, merge, publish,
  distribute, sublicense, and/or sell copies of the Software, and to
  permit persons to whom the Software is furnished to do so, subject to
  the following conditions:

  The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

#if defined(_WIN32)
#include <windows.h>
#else
#include <unistd.h>
#include <sys/mman.h>
#endif

#include <vmalloc.h>

static char rcsid[] = "$Id: vmdcmmap.c 2 2007-03-29 14:43:55Z zeljko.vrba $";

/*
  A vmalloc discipline to get memory by anonymous mmap on UNIX or VirtualAlloc
  on WIN32. The WIN32 code is copied from AT&T's original vmbest.c.

  @todo Rewrite to use mmap of /dev/zero instead of anonymous mmaps. But only
  if other platforms don't support it.
*/
static Void_t *memoryf(
	Vmalloc_t *vm, Void_t *caddr,
	size_t csize, size_t nsize,
	Vmdisc_t *disc)
{
#if defined(_WIN32)
	if(csize == 0)
        return (Void_t*)VirtualAlloc(NIL(LPVOID),nsize,MEM_COMMIT,PAGE_READWRITE);
    if(nsize == 0)
        return VirtualFree((LPVOID)caddr,0,MEM_RELEASE) ? caddr : NIL(Void_t*);
    return NIL(Void_t*);
#else
	void *retval;

	/* old size 0; allocate new memory */
	if(csize == 0) {
		retval = mmap(NULL, nsize, PROT_READ | PROT_WRITE,
					  MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
		return retval == MAP_FAILED ? NULL : retval;
	}

	/* new size 0; free old memory */
	if(nsize == 0) {
		return munmap(caddr, csize) < 0 ? NULL : caddr;
	}

	/* mremap(2) is not portable; currently resize isn't supported */
	return NULL;
#endif
}

/*
  Our memory requirements are very large so declare to allocate memory in
  multiples of 64M = (1<<26).
*/
static Vmdisc_t _vmdcmmap = { memoryf, NULL, 1<<26 };
Vmdisc_t *Vmdcmmap = &_vmdcmmap;
